home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / simula / books / books.lha / kirkerud / guess.sim < prev    next >
Text File  |  1993-08-16  |  2KB  |  46 lines

  1. ! Example 3.9;
  2.  
  3. begin 
  4.  
  5.   integer   guess, below, above, number_of_guesses;
  6.   Boolean   guessed_the_number;
  7.   character given_char;
  8.  
  9.   outtext( "Think of an integer bigger than 0 and less than 1000");
  10.   outimage;
  11.  
  12.   below := 0; above := 1000;
  13.     !  These values are such that below < unknown number < above;
  14.   guessed_the_number := false;
  15.   number_of_guesses  := 0;
  16.  
  17.   while not guessed_the_number do
  18.     begin
  19.         !  Here the following condition always holds:
  20.         !      below <  unknown number < above;
  21.       guess := (below + above)//2;
  22.         ! A good guess when nothing else is known,
  23.         ! is that the unknown is in the middle;
  24.       number_of_guesses := number_of_guesses + 1;
  25.       outtext( "Is it "); outint(guess, 0); outchar('?');  outimage;
  26.       outtext("   If it is, type y."); outimage;
  27.       outtext("   If not, type + if the guess is too small,"
  28.               "   type - if it is too large> ");  breakoutimage;
  29.       inimage; given_char := inchar;
  30.       if given_char = 'y' then    guessed_the_number := true else
  31.       if given_char = '+' then below := guess  else above := guess;
  32.         !  If the guess was not correct, this change of either below or above
  33.         !  is such that the condition
  34.         !      below < unknown number < above
  35.         !  still holds.
  36.         !  Furthermore, the distance from below to above is less
  37.         !  than it was.  This means that progress is made, and sooner
  38.         !  or later there can only be room for one integer between below
  39.         !  and above. A correct ``guess'' will then be made the next time.;
  40.     end;
  41.  
  42.   outtext( "The unknown number was found after only ");
  43.   outint(number_of_guesses, 0); outtext( " guesses!");  outimage;
  44.  
  45. end
  46.